﻿using AxShockwaveFlashObjects;
using ShockwaveFlashObjects;
using Signage01.dao;
using Signage01.Dialogs;
using Signage01.rectangles;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms.Integration;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Telerik.Windows.Controls.Gauge;
using Telerik.Windows.Controls.Map;
using System.Windows.Threading;
using Signage01.util;
using System.Windows.Media.Animation;
using System.Diagnostics;
using System.Timers;
using System.Threading;

namespace Signage01
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		private bool flagNavigationPanelShow = true;
		private bool flagNavigationPanelTimelineShow = true;
		GridLengthConverter gridLengthConverter;
		
		//
		private Double lastSavedWidthTimelineCol = new Double();
		
		private bool draggedTimeline = false;
		private ArrayList listFileName = new ArrayList();
		
		
		List<Screen> listScreen;
		List<Campaign> listCampaign;
		List<int> listScreenTemplateHighestIndex; // this variable is used for incremental screen template indexing

		Screen screenSelected = null;
		public ScreenTemplate screenTemplateSelected = null;
		public ScreenDivision screenDivisionSelected = null;
		public double resourceYPosition;
		
		public Timeline timelineSelected = null;
		public Campaign campaignSelected = null;
		public Channel channelSelected = null;
  
		int selectedindexScreenTemplate = 0;
		int selectedindexScreenDivision = 0;
		List<ScreenTemplate> listScreenTemplate;
		List<ScreenTemplate> listAllScreenTemplates;
		List<Timeline> listTimeline;
		List<Rectangle> listChannelRectangle;

		enum Sides { Up, Down, Left, Right, None };
	   
		
		// variables for rectangle resize
		public ScreenDivision screenDivResizeSelected = null;
		
		// 
		// creating object for drawing
		Drawing drawing;
		//
		// winformhost and axswf
		WindowsFormsHost host;
		AxShockwaveFlash axswf;
		
		// dao
		// 
		//
		private int flagDelete = -1;
		//
		// listview drag/drop to canvas variables
		Point startPoint;
		public double xDragRectangleTimeline;
		public double yDragRectangleTimeline;
		public Rectangle rectangleResourceCurrent;

		public String resourceFileName;
		public int channelVerticalLength=40;

		public RectangleResource rectangleResourceSelected = null;
		public RectangleResourceGraphics rectangleResourceGraphicsSelected = null;

		public MediaElement mediaElementCanvasCampaign = null;
		//
		public TimeSpan newTimeSpan { get; set; }
		//
		List<string> listImageExtention = new List<string>();
		List<string> listVideoExtention = new List<string>();
		LocalFile localFileGlobal=null;
		MediaElement myMediaElement = null;
		int indexCurrentVideoFile = 0;
		string pathCurrentVideoFile = null;
		List<LocalFile> listAllVideoFiles = new List<LocalFile>();
		//
		public bool flagCamapaignOn = false;
		TimelineComponent timelinecomponent = null;

		// variables for canvas campaign timer
		private DispatcherTimer timerCampaign;
		private int timeSecond;
		//font size list
		public List<string> fontsizeList {get; set;}

		RSSSource rssSourceSelected;
		ResourceRSS resourceRSS;
		bool isRssBold = false;
		bool isRssUnderline = false;
		bool isRssItalic = false;
		Color rssColor = System.Windows.Media.Colors.Black;
		string rssFontFamily = null;
		public Storyboard storyBoardCampaignCanvas = null;
		private System.Timers.Timer timerCampaign2;
        private Thread threadRSS;
        // 
        ResourceText resourceText;

		public MainWindow()
		{
			try
			{
				
				InitializeComponent();
				fontsizeList = new List<string> { "8", "10", "12", "14", "16", "18", "20", "22", "24", "26", "28", "36", "48", "72", "127" };
				//comboboxFontSize.ItemsSource = fontsizeList;
				gridLengthConverter = new GridLengthConverter();
				initializeImageVideoTypeList();
				loadFilesFromResource();
				listScreenTemplate = new List<ScreenTemplate>();
				//loadTimeline();
				loadAllScreenTemplatesFromFile();
				initializeDrawing();

				initializeListScreenTemplateHighestIndex();
				initializeListScreen();
				//gaugeLinearScale.LabelFormat = "{}{0:hh:mm}";
				initializeListCampaign();
				initializeRSSTypes();
				//drawGraphics();
					
				//Console.WriteLine("relative x: " + timelineScale.RelativeX);
				// code for campaign canvas timer                
				//                
			}
			catch (Exception ex)
			{
				Console.WriteLine("error is: " + ex.ToString());
			}
			
		}
	   

		public void initializeRSSTypes()
		{
			List<string> listRSSTitle = RssUtil.getAllTitles();            
			comboboxRSSSource.ItemsSource = listRSSTitle;
		}

		public void stopCampaignTimer()
		{
			timeSecond = 0;
			if (timerCampaign != null)
			{
				timerCampaign.Stop();
			}
			timeSpanUpDown.Value = TimeSpan.FromSeconds(timeSecond);
		}

		public void initializeCampaignTimer()
		{
			timeSecond = 0;
			/*
			if (timerCampaign != null)
			{
				timerCampaign.Stop();
			}
			timerCampaign = new DispatcherTimer();
			timerCampaign.Interval = TimeSpan.FromSeconds(1);
			timeSpanUpDown.Value = TimeSpan.FromSeconds(timeSecond);
			timerCampaign.Tick += tick;
			timerCampaign.Start();
			 */
			if (timerCampaign2 != null)
			{
				timerCampaign2.Enabled = false;
			}
			timerCampaign2 = new System.Timers.Timer();
			timerCampaign2.Interval = 1000;
			timeSpanUpDown.Value = TimeSpan.FromSeconds(timeSecond);
			timerCampaign2.Elapsed += tick;
			timerCampaign2.Enabled = true;

		}

		private void initializeImageVideoTypeList()
		{
			listImageExtention.Add("jpg");
			listImageExtention.Add("jpeg");
			listImageExtention.Add("png");
			listImageExtention.Add("bmp");
			
			listVideoExtention.Add("flv");
			listVideoExtention.Add("mp4");
			listVideoExtention.Add("avi");
		}
		private void initializeListCampaign()
		{
			CampaignDAO campaignDAO = CampaignDAO.getSingleTon();
			listCampaign = campaignDAO.getAll();
			listViewCampaign.ItemsSource = listCampaign;
			
			// if the campaign list contains only one campaign, that campaign gets the default selection
			if (listCampaign.Count == 1)
			{
				listViewCampaign.SelectedIndex = 0;
			}
		}

		private void initializeListScreen()
		{
			ScreenDAO screenDAO = ScreenDAO.getSingleTon();
			listScreen = screenDAO.getAll();
			listViewScreen.ItemsSource = listScreen;

			ICollectionView view = CollectionViewSource.GetDefaultView(listViewScreen.ItemsSource);
			view.Refresh();
		}

		private void initializeDrawing()
		{
			drawing = new Drawing(this);
			//drawing.initializeAllRectangles(listScreenTemplate);
			drawing.initializeAllRectangles(listAllScreenTemplates);
		}

		private void initializeListScreenTemplateHighestIndex()
		{
			try
			{               
				ScreenTemplateLastIndexDAO screenTemplateLastIndexDAO = ScreenTemplateLastIndexDAO.getSingleTon();
				listScreenTemplateHighestIndex = screenTemplateLastIndexDAO.getAll();
				if (listScreenTemplateHighestIndex.Count != 0) // the list has been populated before
				{
					listScreenTemplateHighestIndex = screenTemplateLastIndexDAO.getAll();
				}
				else
				{
					ScreenDAO screenDAO = ScreenDAO.getSingleTon();
					listScreen = screenDAO.getAll();

					foreach (Screen sc in listScreen)
					{
						listScreenTemplateHighestIndex.Add(0);
					}

				}
			}
			catch (Exception ex)
			{                
				foreach (Screen sc in listScreen)
				{
					listScreenTemplateHighestIndex.Add(0);
				}
			}
		}

		private void loadThumbnailGrid()
		{
			String[] resourceFileS = Directory.GetFiles("Resources");


			for (int i = 0; i < resourceFileS.Length; i++)
			{
				String[] splittedString = resourceFileS[i].Split('\\');

				LocalFile localFile = new LocalFile();

				string fileNameWithExt = splittedString[splittedString.Count() - 1];
				string[] splittedFileName = fileNameWithExt.Split('.');
				localFile.FileName = splittedFileName[0];
				localFile.FileExt = splittedFileName[1];

				FileInfo fileInfo = new FileInfo(resourceFileS[i]);
				localFile.FileSize = fileInfo.Length;

				
				
				//this.Thumbnails.Items.Add(new BitmapImage(new Uri(fileInfo.FullName)));

			}
		}

		private void loadFilesFromResource()
		{
			String[] resourceFileS = Directory.GetFiles("Resources");


			for (int i = 0; i < resourceFileS.Length;i++ )
			{
				String[] splittedString = resourceFileS[i].Split('\\');

				localFileGlobal = new LocalFile();
				//localFileGlobal = localFile;

				string fileNameWithExt = splittedString[splittedString.Count() - 1];
				string[] splittedFileName = fileNameWithExt.Split('.');
				localFileGlobal.FileName = splittedFileName[0];
				localFileGlobal.FileExt = splittedFileName[1];

				FileInfo fileInfo = new FileInfo(resourceFileS[i]);
				localFileGlobal.FileSize = fileInfo.Length;

				//get time duration
				foreach (string tempExt in listImageExtention)
				{
					if (localFileGlobal.FileExt.EndsWith(tempExt))
					{
						localFileGlobal.TimeDuration = 20;
						this.listViewFile.Items.Add(localFileGlobal);
					}
				}

				foreach (string tempExt in listVideoExtention)
				{
					if (localFileGlobal.FileExt.EndsWith(tempExt))
					{
						listAllVideoFiles.Add(localFileGlobal);
						/*
						myMediaElement = new MediaElement();
						string strURI = System.AppDomain.CurrentDomain.BaseDirectory + "Resources\\" + localFileGlobal.FileName + "." + localFileGlobal.FileExt;
						myMediaElement.Source = new Uri(strURI, UriKind.Absolute);
						myMediaElement.LoadedBehavior = MediaState.Manual;
						myMediaElement.UnloadedBehavior = MediaState.Manual;
						myMediaElement.Pause();
						myMediaElement.MediaOpened += new RoutedEventHandler(media_opened);
						//localFileGlobal.TimeDuration = localFileGlobal.TimeDuration;
						break;
						 */
					}
				}

				this.listFileName.Add(fileNameWithExt);
				
				
			}

			initializeMediaElement();

			foreach (LocalFile localFileTemp in listAllVideoFiles)
			{
				this.listViewFile.Items.Add(localFileTemp);
				
			}

			   


		}
		private void initializeMediaElement()
		{
			myMediaElement = new MediaElement();
			//string strURI = System.AppDomain.CurrentDomain.BaseDirectory + "Resources\\" + localFileGlobal.FileName + "." + localFileGlobal.FileExt;
			//myMediaElement.Source = new Uri(strURI, UriKind.Absolute);
			myMediaElement.LoadedBehavior = MediaState.Manual;
			myMediaElement.UnloadedBehavior = MediaState.Manual;
			myMediaElement.Pause();
			myMediaElement.MediaOpened += new RoutedEventHandler(media_opened);

			myMediaElement.Source = new Uri(System.AppDomain.CurrentDomain.BaseDirectory + "Resources\\"+listAllVideoFiles[0].FileName+"."+listAllVideoFiles[0].FileExt, UriKind.Absolute);

		}
		private void media_opened(object sender, RoutedEventArgs e)
		{
			//Console.WriteLine("media opened");

			//if (myMediaElement.NaturalDuration.HasTimeSpan)
			{
				//localFileGlobal.TimeDuration = Convert.ToInt32(myMediaElement.NaturalDuration.TimeSpan.TotalSeconds);
				listAllVideoFiles[indexCurrentVideoFile].TimeDuration = Convert.ToInt32(myMediaElement.NaturalDuration.TimeSpan.TotalSeconds);
				//Console.WriteLine("timespan for " + listAllVideoFiles[indexCurrentVideoFile].FileName + ",duration:" + listAllVideoFiles[indexCurrentVideoFile].TimeDuration);
				setSource();
			}            
			
		}

		private void media_opened_2(object sender, RoutedEventArgs e)
		{
			listAllVideoFiles[indexCurrentVideoFile].TimeDuration = Convert.ToInt32(myMediaElement.NaturalDuration.TimeSpan.TotalSeconds);
			Console.WriteLine("timespan for " + listAllVideoFiles[indexCurrentVideoFile].FileName + ",duration:" + listAllVideoFiles[indexCurrentVideoFile].TimeDuration);
			indexCurrentVideoFile++;
		}

		private void setSource()
		{
			indexCurrentVideoFile++;
			if (indexCurrentVideoFile == listAllVideoFiles.Count())
				return;
			myMediaElement.Source = new Uri(System.AppDomain.CurrentDomain.BaseDirectory + "Resources\\" + listAllVideoFiles[indexCurrentVideoFile].FileName+"."+listAllVideoFiles[indexCurrentVideoFile].FileExt, UriKind.Absolute);
		}

		/*
		private void loadTimeline()
		{
			TimelineDAO timelineDao = TimelineDAO.getTimelineSingleTon();
			listTimeline = timelineDao.getTimelineObject();
			listviewTimeline.ItemsSource = null;
			listviewTimeline.ItemsSource = listTimeline;
			
		}
		*/
		private void loadAllScreenTemplatesFromFile()
		{
			ScreenTemplateDAO screentempDao = ScreenTemplateDAO.getSingleTon();
			listAllScreenTemplates = screentempDao.getAll();
			//listScreenTemplate = screentempDao.getAll();
		}


		private void Button_Click_1(object sender, RoutedEventArgs e)
		{
			if (flagNavigationPanelShow)
			{                
				leftColumnDefinition.Width = (GridLength)gridLengthConverter.ConvertFromString("4*");
				labelNavigation.Content = "";
				buttonNavigationShow.Content = "Show";
				flagNavigationPanelShow = false;
			}
			else
			{
				leftColumnDefinition.Width = (GridLength)gridLengthConverter.ConvertFromString("20*");
				labelNavigation.Content = "Navigation";
				buttonNavigationShow.Content = "Hide";
				flagNavigationPanelShow = true;
			}
		}

		private void Button_Click_2(object sender, RoutedEventArgs e)
		{
			if (flagNavigationPanelTimelineShow)
			{
				timelineColumnDefinition.Width = (GridLength)gridLengthConverter.ConvertFrom(40.0);

				
				
				buttonNavigationShowTimeline.Content = "Show";
				flagNavigationPanelTimelineShow = false;
			}
			else
			{
				if (draggedTimeline)
				{
					timelineColumnDefinition.Width = (GridLength)gridLengthConverter.ConvertFrom(lastSavedWidthTimelineCol);
					draggedTimeline = false;
				}
				else
				{
					timelineColumnDefinition.Width = (GridLength)gridLengthConverter.ConvertFromString("20*");
				}



				buttonNavigationShowTimeline.Content = "Hide";
				flagNavigationPanelTimelineShow = true;
			}
		}

		private void drag_splitter_c2(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
		{
		   
			lastSavedWidthTimelineCol = (Double)timelineColumnDefinition.Width.Value;
			//MessageBox.Show(Convert.ToString(lastSavedWidthTimelineCol));
			draggedTimeline = true;
		}

		private void Button_Add_Click_1(object sender, RoutedEventArgs e)
		{
			(sender as System.Windows.Controls.Button).ContextMenu.IsEnabled = true;
			(sender as System.Windows.Controls.Button).ContextMenu.PlacementTarget = (sender as System.Windows.Controls.Button);
			(sender as System.Windows.Controls.Button).ContextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
			(sender as System.Windows.Controls.Button).ContextMenu.IsOpen = true;
		}

		private void MenuItem_Click_1(object sender, RoutedEventArgs e)
		{
			Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();

			openFileDialog.Filter = "Image files (.bmp,.jpg,.png) |*.bmp;*.jpg;*.png | SWF Files (.swf) | *.swf | Video Files (.avi,.flv,.mov,.mkv) | *.avi;*.flv;*.mov;*.mkv | All Files | *.*";

			Nullable<bool> result = openFileDialog.ShowDialog();

			if (result == true)
			{
				//string fileName = openFileDialog.FileName;
				LocalFile localFile = new LocalFile();
				string filePath = openFileDialog.FileName;
				string[] splittedString = filePath.Split('\\');

				string fileNameWithExt = splittedString[splittedString.Count() - 1];
				string[] splittedFileName = fileNameWithExt.Split('.');
				localFile.FileName = splittedFileName[0];
				localFile.FileExt = splittedFileName[1];

				FileInfo fileInfo = new FileInfo(filePath);
				localFile.FileSize = fileInfo.Length;

				foreach (string tempExt in listImageExtention)
				{
					if (localFile.FileExt.EndsWith(tempExt))
					{
						localFile.TimeDuration = 20;
						
					}
				}

				foreach (string tempExt in listVideoExtention)
				{
					if (localFile.FileExt.EndsWith(tempExt))
					{
						listAllVideoFiles.Add(localFile);
						
						myMediaElement = new MediaElement();
						string strURI = System.AppDomain.CurrentDomain.BaseDirectory + "Resources\\" + localFile.FileName + "." + localFile.FileExt;
						myMediaElement.Source = new Uri(strURI, UriKind.Absolute);
						myMediaElement.LoadedBehavior = MediaState.Manual;
						myMediaElement.UnloadedBehavior = MediaState.Manual;
						myMediaElement.Pause();
						myMediaElement.MediaOpened += new RoutedEventHandler(media_opened_2);
						//localFileGlobal.TimeDuration = localFileGlobal.TimeDuration;
						//break;
						 
					}
				}

				this.listFileName.Add(fileNameWithExt);

				//this.Thumbnails.Items.Add(new BitmapImage(new Uri(fileInfo.FullName)));

				this.listViewFile.Items.Add(localFile);                

				/*
				foreach (LocalFile localFileTemp in listAllVideoFiles)
				{
					this.listViewFile.Items.Add(localFileTemp);

				}
				*/
				if (Directory.Exists("resources"))
				{
					File.Copy(filePath, "resources\\" + fileNameWithExt,true);
				}
			}
		}

		private void buttonDelete_Click_1(object sender, RoutedEventArgs e)
		{
			if (listViewFile.SelectedItem != null)
			{
				int selIndex = listViewFile.SelectedIndex;
				string selFileName = listFileName[selIndex] as string;
				Console.WriteLine("selected file name:" + selFileName);
				File.Delete("resources\\" + selFileName);

				listViewFile.Items.RemoveAt(selIndex);
				listFileName.RemoveAt(selIndex);
			}
			else
			{
				System.Windows.MessageBox.Show("Select an item to delete first");
			}
		}

		private void Button_Add_Screen_Click_1(object sender, RoutedEventArgs e)
		{
			/*
			rightGridFirstRow.Height = new GridLength(0, GridUnitType.Pixel);
			rightGridSecRow.Height = new GridLength(0, GridUnitType.Auto);
			rightGridThrdRow.Height = new GridLength(100, GridUnitType.Star);
			 */
			rightGrid2.Visibility = Visibility.Visible;
			rightGrid.Visibility = Visibility.Collapsed;
			ScreenTypeGrid.Visibility = Visibility.Visible;

			// populate listviewscreen
			
			// retrieving the list from the file
			//ScreenDAO screenDAO = ScreenDAO.getSingleTon();
			//List<Screen> listScreen = screenDAO.getAll();

			//listViewScreen.ItemsSource = listScreen;

			

			// end populate listviewscreen
	
		}

		private void TreeViewItem_MouseDoubleClick_1(object sender, MouseButtonEventArgs e)
		{
			rightGrid2.Visibility = Visibility.Collapsed;
			rightGrid.Visibility = Visibility.Visible;
			ScreenTypeGrid.Visibility = Visibility.Collapsed;
			CampaignListGrid.Visibility = Visibility.Visible;
		}

		private void CampaignItem_Collapsed_1(object sender, RoutedEventArgs e)
		{
			CampaignItem.IsExpanded = true;
		}

		private void Button_Add_Screen_Click_2(object sender, RoutedEventArgs e)
		{

		}

		private void Button_Add_Screen_Type_Click_1(object sender, RoutedEventArgs e)
		{

		}

		private void Button_Add_Screen_Type_Click_2(object sender, RoutedEventArgs e)
		{
			// add screen type            
			AddScreenWindow screenWindow = new AddScreenWindow(listScreen);
			screenWindow.Owner = this;
			screenWindow.Owner.ShowActivated = false;
			bool? result = screenWindow.ShowDialog();
			
		   
			if (result != null)
			{
				if (result == true)
				{
					/*
					string serializationFile = "resources/screen/screen.bin";
					// List<Screen> listScreen;

					// retrieving the list from the file
					try
					{
						using (Stream stream = File.Open(serializationFile, FileMode.Open))
						{
							var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

							// if this line throws exception, the file is empty, so we have to create a new list in catch block
							listScreen = (List<Screen>)bformatter.Deserialize(stream);
						}
					}
					catch (Exception ex)
					{
						Console.WriteLine("The file is empty");
						listScreen = new List<Screen>();
					}
					*/
					//Console.WriteLine("Screen list size: " + listScreen.Count);
					//listViewScreen.ItemsSource = null;
					ScreenDAO screenDAO = ScreenDAO.getSingleTon();
					listScreen = screenDAO.getAll();
					listViewScreen.ItemsSource = listScreen;

					ICollectionView view = CollectionViewSource.GetDefaultView(listViewScreen.ItemsSource);
					view.Refresh();
	
				}
			}
		}

		private void buttonDeleteScreen_Click_1(object sender, RoutedEventArgs e)
		{
			MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("Are you sure?", "ScreenTemplate Delete Confirmation", System.Windows.MessageBoxButton.YesNo);
			if (messageBoxResult == MessageBoxResult.Yes)
			{
				ScreenDAO screenDAO = ScreenDAO.getSingleTon();
				Screen screenToBeDeleted = listViewScreen.SelectedItem as Screen;
				screenDAO.deleteScreen(screenToBeDeleted);
				listScreen = screenDAO.getAll();

				listViewScreen.ItemsSource = listScreen;
				ICollectionView view = CollectionViewSource.GetDefaultView(listViewScreen.ItemsSource);
				view.Refresh();
			}

		}

		private void Button_Add_Screen_Templdate_Click_1(object sender, RoutedEventArgs e)
		{
			if (screenSelected == null)
			{
				System.Windows.MessageBox.Show("Select a screen first!");
			}
			else
			{
				ScreenTemplate st = new ScreenTemplate(screenSelected);
				//int currentSTindex = listScreenTemplate.Count;
				int indexScreen = listScreen.IndexOf(screenSelected);
				int indexScreenTemplate = listScreenTemplateHighestIndex[indexScreen];
				listScreenTemplateHighestIndex[indexScreen]++;
					
				st.Name = "ScreenTemplate" + indexScreenTemplate;
				listScreenTemplate.Add(st);
				listAllScreenTemplates.Add(st);
				//Console.WriteLine("No: " + listScreenTemplate.Count());
				treeViewScreenTemplate.ItemsSource = null;
				treeViewScreenTemplate.ItemsSource = listScreenTemplate;
				//Button_Reload_Screen_Template_Click_1(sender, e);
				

			}
			
		}

		private void Button_Delete_Screen_Templdate_Click_1(object sender, RoutedEventArgs e)
		{
			MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("Are you sure?", "ScreenTemplate Delete Confirmation", System.Windows.MessageBoxButton.YesNo);
			if (messageBoxResult == MessageBoxResult.Yes)
			{
				if (flagDelete == 0)
				{
					ScreenTemplate st = (ScreenTemplate)treeViewScreenTemplate.SelectedItem;

					int deleteIndex = -1;
					int index = 0;
					foreach (ScreenTemplate tempScreenTemplate in listAllScreenTemplates)
					{
						if (tempScreenTemplate.Name == st.Name && tempScreenTemplate.ScreenObject.ScreenName == st.ScreenObject.ScreenName)
						{
							deleteIndex = index;
						}
						index++;
					}

					listAllScreenTemplates.RemoveAt(deleteIndex);

					listScreenTemplate = getScreenTemplateForScreen(screenSelected);

					treeViewScreenTemplate.ItemsSource = null;
					treeViewScreenTemplate.ItemsSource = listScreenTemplate;

					ScreenTemplateDAO screenTemplateDAO = ScreenTemplateDAO.getSingleTon();
					screenTemplateDAO.saveListToFile(listAllScreenTemplates);

					
				}
				else if(flagDelete == 1)
				{
					ScreenDivision screenDivisionToBeDeleted = (ScreenDivision)treeViewScreenTemplate.SelectedItem;

					ScreenTemplate screenTemplate = getScreenTemplateFromSelectedScreenDiv(screenDivisionToBeDeleted);

					int index = 0;
					int deleteIndex = -1;
					foreach (ScreenDivision sd in screenTemplate.ListScreenDivision)
					{
						if (sd == screenDivisionToBeDeleted)
						{
							deleteIndex = index;
						}
						index++;
					}

					screenTemplate.ListScreenDivision.RemoveAt(deleteIndex);

					treeViewScreenTemplate.ItemsSource = null;
					treeViewScreenTemplate.ItemsSource = listScreenTemplate;

					ScreenTemplateDAO screenTemplateDAO = ScreenTemplateDAO.getSingleTon();
					screenTemplateDAO.saveListToFile(listAllScreenTemplates);

					MessageBox.Show("Screen Division deleted!");
				}
			}
		}

		private void listViewScreen_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
		{
			if (listViewScreen.SelectedItem != null)
			{
				screenSelected = listViewScreen.SelectedItem as Screen;
				textBoxScreenName.Text = screenSelected.ScreenName;
				textBoxScreenWidth.Text = Convert.ToString(screenSelected.Width);
				textBoxScreenHeight.Text = Convert.ToString(screenSelected.Height);
				gridScreenProperty.Visibility = Visibility.Visible;
				gridScreenTemplateProperty.Visibility = Visibility.Collapsed;
				gridTextBoxBindindingchange();
				gridScreenDivisionProperty.Visibility = Visibility.Collapsed;


				//listScreenTemplate = ScreenTemplate.getScreenTemplateObjectFromResource(screenSelected);
				listScreenTemplate = getScreenTemplateForScreen(screenSelected);

				treeViewScreenTemplate.ItemsSource = null;
				treeViewScreenTemplate.ItemsSource = listScreenTemplate;
				//treeViewScreenTemplate.ItemsSource = listAllScreenTemplates;
				//treeViewScreenTemplate.UpdateLayout();

				// if the treeview is populated, select the first screen template


				if (treeViewScreenTemplate.Items.Count != 0)
				{
					//TreeViewItem treeViewItemSelected = (TreeViewItem)treeViewScreenTemplate.ItemContainerGenerator.ContainerFromItem(treeViewScreenTemplate.Items[0]);

				}

				canvas.Children.Clear();

				// this portion is necessary to pre-select first screentemplate for a specied screen, otherwise
				// initially no screen template gets selected, and the canvas remains empty
				if (listScreenTemplate.Count() > 0)
				{
					ScreenTemplate st = (ScreenTemplate)treeViewScreenTemplate.Items[0];
					canvas.Children.Clear();
					drawing.rectangleDrawForScreenDiv(listScreenTemplate[0].ListScreenDivision);
				}

				gridScreenProperty.Visibility = Visibility.Visible;
				gridScreenTemplateProperty.Visibility = Visibility.Collapsed;
				gridTextBoxBindindingchange();
				gridScreenDivisionProperty.Visibility = Visibility.Collapsed;

				// 
				canvas.Width = screenSelected.Width;
				canvas.Height = screenSelected.Height;
				canvas.UpdateLayout();
			}
		}
		 private List<ScreenTemplate> getScreenTemplateForScreen(Screen screenToFilter)
		{
			List<ScreenTemplate> filteredListScreenTemplate = new List<ScreenTemplate>();
						
					foreach(ScreenTemplate st in listAllScreenTemplates)
					//foreach (ScreenTemplate st in listScreenTemplate)  
					{
						//if (st.ScreenObject == screenToFilter)
						if (st.ScreenObject.ScreenName.Equals(screenToFilter.ScreenName))
						{
							filteredListScreenTemplate.Add(st);
						}
					}
					return filteredListScreenTemplate;
		}

		// tree nodes node=>tree
		


		private void treeViewScreenTemplate_SelectedItemChanged_1(object sender, System.Windows.RoutedPropertyChangedEventArgs<object> e)
		{
			//Console.WriteLine("selection changed");
			//MessageBox.Show(((TreeViewItem)e.NewValue).Header.ToString());
			if (treeViewScreenTemplate.ItemsSource != null)
			{
				try
				{
					
					if (e.NewValue.GetType() == typeof(ScreenTemplate))
					{
						//Console.WriteLine("st selected");


						ScreenTemplate st = (ScreenTemplate)e.NewValue;

						gridScreenProperty.Visibility = Visibility.Collapsed;


						gridTextBoxBindindingchange();
						gridScreenDivisionProperty.Visibility = Visibility.Collapsed;
						
						gridScreenTemplateProperty.Visibility = Visibility.Visible;

						textBoxScreenTemplateName.Text = st.Name;
						
						screenTemplateSelected = st;

						selectedindexScreenTemplate = listScreenTemplate.IndexOf(st);
						//listScreenTemplate[selectedindexScreenTemplate].IsSelected = true;                        
						screenTemplateSelected.IsSelected = true;


						//drawing.setRectangleDraw(screenTemplateSelected);
						canvas.Children.Clear();

						List<ScreenDivision> listScreenDivision = screenTemplateSelected.ListScreenDivision;
						//Console.WriteLine("screen div size:" + listScreenDivision.Count());
						
						flagDelete = 0; // screentemplate to be deleted
						drawing.rectangleDrawForScreenDiv(listScreenDivision);
						//canvas.UpdateLayout();
					}// if ended
					else if (e.NewValue.GetType() == typeof(ScreenDivision))
					{
						//Console.WriteLine("sd selected");
						ScreenDivision sd = (ScreenDivision)e.NewValue;
						screenDivisionSelected = sd;
						ScreenTemplate screenTemplateParent = getScreenTemplateFromSelectedScreenDiv(sd);                        
						drawing.selectScreenDivProgramatically(sd);

						/*
						screenTemplateParent.IsSelected = true;
						screenTemplateParent.IsSelected = false;                        
						sd.IsSelected = true;
						*/
						

					   /*
						ScreenDivision sd = (ScreenDivision)treeViewScreenTemplate.SelectedItem;
						
						ScreenTemplate st = (ScreenTemplate)treeViewScreenTemplate.Items[0];
						ScreenDivision tempDiv = st.ListScreenDivision[1];

						if (tempDiv == sd)
						{
							Console.WriteLine("match");
						}
						*/
						//MessageBox.Show(((TreeViewItem)e.NewValue).Header.ToString());
						//Console.WriteLine(e.NewValue.GetType());
						/*
						if (treeViewItem != null)
						{
							Console.WriteLine("yeh");
						}
						*/

						/*
						ScreenDivision selectedSD = (ScreenDivision)treeViewScreenTemplate.SelectedItem;
						//TreeViewItem parentItem = (TreeViewItem)selectedTreeViewItem.Parent;
						//TreeViewItem tvi = (TreeViewItem)treeViewScreenTemplate.ItemContainerGenerator.ContainerFromItem(treeViewScreenTemplate.SelectedItem);
						//ScreenTemplate selectedSDParent  = tvi.Parent as ScreenTemplate;
						//TreeViewItem tviParent = (TreeViewItem)treeViewScreenTemplate.ItemContainerGenerator.ContainerFromItem(selectedSD);
						


						Console.WriteLine("parent type is: " + tvi.GetValue());

						

						ScreenDivision sd = (ScreenDivision)e.NewValue;
						
						//Console.WriteLine((((TreeViewItem)((TreeView)sender).SelectedItem).Parent).GetType());
						
						*/
						

						//gridScreenProperty.Visibility = Visibility.Collapsed;
						//gridScreenDivisionProperty.Visibility = Visibility.Visible;
						//gridScreenTemplateProperty.Visibility = Visibility.Collapsed;

						flagDelete = 1; // screendiv to be deleted
						textBoxScreenDivisionName.Text = sd.Name;
						
						textBoxStartX.Text = Convert.ToString(sd.RectangleDiv.X);
						textBoxStartY.Text = Convert.ToString(sd.RectangleDiv.Y);
						textBoxWidth.Text = Convert.ToString(sd.RectangleDiv.Width);
						textBoxHeight.Text = Convert.ToString(sd.RectangleDiv.Height);
						textBoxZOrder.Text = Convert.ToString(sd.RectangleDiv.ZIndex);
						 
					 }
					
				}
				catch (Exception ex)
				{
				}

			}

			
		}

		private ScreenTemplate getScreenTemplateFromSelectedScreenDiv(ScreenDivision screenDivision)
		{
			ScreenTemplate screenTemplate = null;

			for (int i = 0; i < treeViewScreenTemplate.Items.Count; i++)
			{
				ScreenTemplate screenTemplateTemp = (ScreenTemplate)treeViewScreenTemplate.Items[i];

				for (int j = 0; j < screenTemplateTemp.ListScreenDivision.Count; j++)
				{
					ScreenDivision screenDivisionTemp = screenTemplateTemp.ListScreenDivision[j];

					if (screenDivisionTemp == screenDivision)
					{
						return screenTemplateTemp;
					}
				}
			}

			return null;

		}

		private void buttonAddViewer_Click_1(object sender, RoutedEventArgs e)
		{

		}

		private void zoomCombobox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
		{

		}



		private void textBoxScreenTemplateName_KeyUp_1(object sender, System.Windows.Input.KeyEventArgs e)
		{
			if (e.Key == Key.Enter)
			{
				BindingExpression be = textBoxScreenTemplateName.GetBindingExpression(System.Windows.Controls.TextBox.TextProperty);
				be.UpdateSource();
			}
		}

		

		public void updateScreenDivProperties(ScreenDivision screenDivision)
		{
			
			Rectangle rectangle = drawing.getRectangleDrawFromNumber(screenDivision.RectangleNumber).Rectangle;
			
			textBoxStartX.Text = Convert.ToString(Canvas.GetLeft(rectangle));
			textBoxStartY.Text = Convert.ToString(Canvas.GetTop(rectangle));
			textBoxWidth.Text = Convert.ToString(rectangle.Width);
			textBoxHeight.Text = Convert.ToString(rectangle.Height);
			textBoxZOrder.Text = Convert.ToString(Canvas.GetZIndex(rectangle));
		}

		private void textBoxStartX_KeyUp_1(object sender, System.Windows.Input.KeyEventArgs e)
		{
			if (e.Key == Key.Enter)
			{
				buttonSave_Click_1(sender, e);
			}

		}

		private void textBoxStartY_KeyUp_1(object sender, System.Windows.Input.KeyEventArgs e)
		{
			if (e.Key == Key.Enter)
			{
				buttonSave_Click_1(sender, e);
			}
		}
		
		private void textBoxWidth_KeyUp_1(object sender, System.Windows.Input.KeyEventArgs e)
		{
			if (e.Key == Key.Enter)
			{
				buttonSave_Click_1(sender, e);
			}
		}

		private void textBoxHeight_KeyUp_1(object sender, System.Windows.Input.KeyEventArgs e)
		{
			if (e.Key == Key.Enter)
			{
				buttonSave_Click_1(sender, e);
			}
		}

		private void textBoxZOrder_KeyUp_1(object sender, System.Windows.Input.KeyEventArgs e)
		{
			if (e.Key == Key.Enter)
			{
				buttonSave_Click_1(sender, e);
			}
		}

		private void buttonSave_Click_1(object sender, RoutedEventArgs e)
		{            
			if (this.screenDivisionSelected != null)
			{                
				double x = Convert.ToDouble(textBoxStartX.Text);
				double y = Convert.ToDouble(textBoxStartY.Text);
				double width = Convert.ToDouble(textBoxWidth.Text);
				double height = Convert.ToDouble(textBoxHeight.Text);
				int zIndex = Convert.ToInt32(textBoxZOrder.Text);

				// update screendiv rectangle
				screenDivisionSelected.RectangleDiv.X = x;
				screenDivisionSelected.RectangleDiv.Y = y;
				screenDivisionSelected.RectangleDiv.Width = width;
				screenDivisionSelected.RectangleDiv.Height = height;
				screenDivisionSelected.RectangleDiv.ZIndex = zIndex;
				//

				// update shape rectangle
				Rectangle rectangle = drawing.getRectangleDrawFromNumber(screenDivisionSelected.RectangleNumber).Rectangle;
				Canvas.SetLeft(rectangle, x);
				Canvas.SetTop(rectangle, y);
				rectangle.Width = width;
				rectangle.Height = height;
				Canvas.SetZIndex(rectangle, zIndex);
				//
				rectangle.UpdateLayout();
				canvas.UpdateLayout();             
			}
		}


		private void gridTextBoxBindindingchange()
		{
			if (gridScreenDivisionProperty.Visibility == Visibility.Visible)
			{                
				textBoxStartX.Text = "";
				textBoxStartY.Text = "";
				textBoxWidth.Text = "";
				textBoxHeight.Text = "";
				textBoxZOrder.Text = "";
				
			}
			else
			{                
				textBoxStartX.Text = "{Binding Path=RectangleDiv.X,Mode=TwoWay,UpdateSourceTrigger=Explicit}";
				textBoxStartY.Text = "{Binding Path=RectangleDiv.Y,Mode=TwoWay,UpdateSourceTrigger=Explicit}";
				textBoxWidth.Text = "{Binding Path=RectangleDiv.Width,Mode=TwoWay,UpdateSourceTrigger=Explicit}";
				textBoxHeight.Text = "{Binding Path=RectangleDiv.Height,Mode=TwoWay,UpdateSourceTrigger=Explicit}";
				textBoxZOrder.Text = "{Binding Path=RectangleDiv.ZIndex,Mode=TwoWay,UpdateSourceTrigger=Explicit}";
			}
		}

		private void Button_Add_Screen_Division_Click_1(object sender, RoutedEventArgs e)
		{
			if (screenTemplateSelected == null)
				return;
			List<ScreenDivision> listScreenDivision = screenTemplateSelected.ListScreenDivision;

			int currentIndexScreenDiv = listScreenDivision.Count;

			ScreenDivision screenDivision = new ScreenDivision();
			int indexScreen = listScreen.IndexOf(screenSelected);


			screenDivision.Name = "div " + screenTemplateSelected.LastScreenDivIndex;
			screenTemplateSelected.LastScreenDivIndex++;
			//screenDivision.RectangleNumber = drawing.CountRectangle;
			drawing.LastRectangleNo++;
			screenDivision.RectangleNumber = drawing.LastRectangleNo;
			//Console.WriteLine("new div rect no: " + screenDivision.RectangleNumber);

			RectangleDiv rectangleDiv = new RectangleDiv();
			
			rectangleDiv.X = (currentIndexScreenDiv + 1) * 20;
			rectangleDiv.Y = (currentIndexScreenDiv + 1) * 20;
			rectangleDiv.Width = 200;
			rectangleDiv.Height = 100;
			rectangleDiv.ZIndex = currentIndexScreenDiv;

			screenDivision.RectangleDiv = rectangleDiv;

			if (screenTemplateSelected != null)
			{
				screenTemplateSelected.ListScreenDivision.Add(screenDivision);
				//screenTemplateSelected.ListScreenDivision = listScreenDivision;
			}


			drawing.addRectangleDrawForScreenDiv(listScreenDivision,currentIndexScreenDiv);


		   
			//
			

			listScreenTemplate[selectedindexScreenTemplate] = screenTemplateSelected;
			treeViewScreenTemplate.ItemsSource = null;
			treeViewScreenTemplate.ItemsSource = listScreenTemplate;
			screenTemplateSelected.IsExpanded = true; 
			//
			gridScreenProperty.Visibility = Visibility.Collapsed;
			gridScreenTemplateProperty.Visibility = Visibility.Collapsed;

			gridTextBoxBindindingchange();
			gridScreenDivisionProperty.Visibility = Visibility.Visible;
			
			
		}

		private void buttonCanvasZoom_Click_1(object sender, RoutedEventArgs e)
		{
			canvas.Width *= 2;
			canvas.Height *= 2;
			scaleTransform.ScaleX *= 2;
			scaleTransform.ScaleY *= 2;
		}

		private void buttonCanvasZoomOut_Click_1(object sender, RoutedEventArgs e)
		{
			canvas.Width *= .5;
			canvas.Height *= .5;
			scaleTransform.ScaleX *= .5;
			scaleTransform.ScaleY *= .5;
		}



		private void textBoxScreenDivisionName_KeyUp_1(object sender, System.Windows.Input.KeyEventArgs e)
		{
			if (e.Key == Key.Enter)
			{
				BindingExpression be = textBoxScreenDivisionName.GetBindingExpression(System.Windows.Controls.TextBox.TextProperty);
				be.UpdateSource();
			}
		}

		private void Button_Save_Screen_Template_Click_1(object sender, RoutedEventArgs e)
		{
			//ScreenTemplate.saveScreenTemplateListObjectToResource(listScreenTemplate);
			
			
			// saving screen template indexes
			ScreenTemplateLastIndexDAO screenTemplateLastIndexDAO = ScreenTemplateLastIndexDAO.getSingleTon();
			screenTemplateLastIndexDAO.saveListToFile(listScreenTemplateHighestIndex);
			

			foreach(ScreenTemplate st in listAllScreenTemplates)
			{
				screenTemplateImageSave(st);
				//Console.WriteLine(st.Name + "template image saved");
			}

			ScreenTemplateDAO screenTempDao = ScreenTemplateDAO.getSingleTon();
			int success = screenTempDao.saveListToFile(listAllScreenTemplates);

		   
			List<ScreenTemplate> listTemp = screenTempDao.getAll();

			foreach (ScreenTemplate st3 in listTemp)
			{
				Console.WriteLine("template path: " + st3.ImageFilePath);
			}
			
			MessageBox.Show("Screen Template Collection updated!");
		}

		private void Button_Reload_Screen_Template_Click_1(object sender, RoutedEventArgs e)
		{
			//listScreenTemplate = ScreenTemplate.getScreenTemplateObjectFromResource(screenSelected);
			//treeViewScreenTemplate.ItemsSource = listScreenTemplate; 
		}
	   
		private void Button_Add_Timeline_Click_1(object sender, RoutedEventArgs e)
		{
			if (campaignSelected == null)
			{
				MessageBox.Show("First select a campaign!");
				return;
			}

			campaignSelected = listCampaign[listViewCampaign.SelectedIndex];
			CampaignDAO campaignDAO = CampaignDAO.getSingleTon();
			
			// New timeline is added in this window
			AddTimeline timelineWindow = new AddTimeline(campaignSelected);
			//AddTimeline timelineWindow = new AddTimeline(listScreenTemplate);

			timelineWindow.Owner = this;
			
			timelineWindow.Owner.ShowActivated = false;
			bool? result = timelineWindow.ShowDialog();
			if (result != null)
			{
				if (result == true)
				{
					 /*
					 TimelineDAO timelineDao = TimelineDAO.getTimelineSingleTon();
					 List<Timeline> listTimeline= timelineDao.getTimelineObject();
					 listviewTimeline.ItemsSource = null;
					 listviewTimeline.ItemsSource = listTimeline;
					  */
					List<Timeline> listTimeline = campaignSelected.getTimeline();
					listviewTimeline.ItemsSource = null;
					listviewTimeline.ItemsSource = listTimeline;
					Timeline timelineAdded = (Timeline)listviewTimeline.Items.GetItemAt(listTimeline.Count() - 1);
					timelineAdded.IsSelected = true;
				}
			}

		}

		
		private void screenTemplateImageSave(ScreenTemplate screenTemplate)
		{
			try
			{
				Canvas canvas2 = drawing.getCanvasFromScreenTemplate(screenTemplate);

				Rect bounds = VisualTreeHelper.GetDescendantBounds(canvas2);
				double dpi = 96d;

				Transform trans = canvas2.LayoutTransform;
				canvas2.LayoutTransform = null;

				Size size = new Size(canvas2.Width, canvas2.Height);

				canvas2.Measure(size);
				canvas2.Arrange(new Rect(size));

				RenderTargetBitmap rtb = new RenderTargetBitmap((int)canvas2.Width, (int)canvas2.Height, dpi, dpi, System.Windows.Media.PixelFormats.Default);

				/*
				 DrawingVisual dv = new DrawingVisual();
				 using (DrawingContext dc = dv.RenderOpen())
				 {
					 VisualBrush vb = new VisualBrush(canvas2);
					 dc.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));
				 }
				 */
				rtb.Render(canvas2);

				PngBitmapEncoder png = new PngBitmapEncoder();

				png.Frames.Add(BitmapFrame.Create(rtb));

				string fileName = screenTemplate.Name;

				string screenDirName = screenTemplate.ScreenObject.ScreenName;

				if (!Directory.Exists("Resources/ScreenTemplates/" + screenDirName))
				{
					Directory.CreateDirectory("Resources/ScreenTemplates/" + screenDirName);
				}

				string fullfilepath = "Resources/ScreenTemplates/" + screenDirName + "/" + fileName + ".png";
				using (Stream stm = File.Create("Resources/ScreenTemplates/" + screenDirName + "/" + fileName + ".png"))
				{
					png.Save(stm);
				}
				screenTemplate.ImageFilePath = fullfilepath;
				canvas2.LayoutTransform = trans;
			}
			catch (Exception ex)
			{

			}

		}
		

		private void Button_Save_Screen_Division_Click_1(object sender, RoutedEventArgs e)
		{
			Rect bounds = VisualTreeHelper.GetDescendantBounds(canvas);
			double dpi = 96d;

			RenderTargetBitmap rtb = new RenderTargetBitmap((int)bounds.Width, (int)bounds.Height, dpi, dpi, System.Windows.Media.PixelFormats.Default);


			DrawingVisual dv = new DrawingVisual();
			using (DrawingContext dc = dv.RenderOpen())
			{
				VisualBrush vb = new VisualBrush(canvas);
				dc.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));
			}

			rtb.Render(dv);

			PngBitmapEncoder png = new PngBitmapEncoder();

			png.Frames.Add(BitmapFrame.Create(rtb));

			string screenDirName = screenTemplateSelected.ScreenObject.ScreenName;
			Directory.CreateDirectory("Resources/ScreenTemplates/" + screenDirName);

			string fileName = screenTemplateSelected.Name;
			string fullfilepath = "Resources/ScreenTemplates/" + screenDirName + "/" + fileName + ".png";
			using (Stream stm = File.Create("Resources/ScreenTemplates/" + screenDirName + "/" + fileName + ".png"))
			{
				png.Save(stm);
			}

			screenTemplateSelected.ImageFilePath = fullfilepath;
			listScreenTemplate[selectedindexScreenTemplate] = screenTemplateSelected;
			treeViewScreenTemplate.ItemsSource = null;
			treeViewScreenTemplate.ItemsSource = listScreenTemplate;
			screenTemplateSelected.IsExpanded = true;
			
		}

		private void treeviewitemScreenType_MouseDoubleClick_1(object sender, MouseButtonEventArgs e)
		{
			rightGrid2.Visibility = Visibility.Visible;
			rightGrid.Visibility = Visibility.Collapsed;
			ScreenTypeGrid.Visibility = Visibility.Visible;
			CampaignListGrid.Visibility = Visibility.Collapsed;
		}
		
		public void listviewTimeline_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
		{
			if (listviewTimeline.SelectedItem != null)
			{
				timelineSelected = listviewTimeline.SelectedItem as Timeline;
				textBoxTimelineName.Text = timelineSelected.Name;
				//textBoxTimelineDuration.Text = get2digitFigure(timelineSelected.Hr) + ":" + get2digitFigure(timelineSelected.Min) + ":" + get2digitFigure(timelineSelected.Sec);
				textBoxTimelineDurationHour.Text = get2digitFigure(timelineSelected.Hr);
				textBoxTimelineDurationMin.Text = get2digitFigure(timelineSelected.Min);
				textBoxTimelineDurationSec.Text = get2digitFigure(timelineSelected.Sec);

				gridTimelineProperty.Visibility = Visibility.Visible;
				gridResourceProperty.Visibility = Visibility.Collapsed;
				

				int totalSecond = timelineSelected.Hr * 3600 + timelineSelected.Min * 60 + timelineSelected.Sec;

				//canvasTimeline.Children.Clear();
				drawLinearScaleForTimeLine(totalSecond);
				fillTimelineChannelRight(totalSecond);
				fillTimelineChannelLeft();
				if (Math.Abs(this.campaignCanvas.ActualWidth-0)>0.1)
				{
					this.campaignCanvas.Children.Clear();
					if (timelinecomponent != null)
					{
						timelinecomponent.stop(); 
						//Console.WriteLine("timelinecomponent exists already");
					}
					timelinecomponent = new TimelineComponent(this, timelineSelected);
					flagCamapaignOn = true;
					initializeCampaignTimer();
					
				}
			}
		}

		private void fillTimelineChannelRight(int totalSecond)
		{
			int countChannel = timelineSelected.ScTemplate.ListScreenDivision.Count() + 1;
			listChannelRectangle = new List<Rectangle>();

			for (int i = 0; i < countChannel; i++)
			{
				Rectangle rectangle = new Rectangle();
				listChannelRectangle.Add(rectangle);

				rectangle.Width = totalSecond*10 + 150;
				//rectangle.Height = 30;
				rectangle.Height = channelVerticalLength ;

				Canvas.SetLeft(rectangle, 0);
				//Canvas.SetTop(rectangle, i * 33 + 75);
				Canvas.SetTop(rectangle, i * (channelVerticalLength + 3) + 75);

				rectangle.Stroke = new SolidColorBrush(Color.FromRgb(134,193,237));
				rectangle.Fill = new SolidColorBrush(Color.FromRgb(134, 193, 237));

				rectangle.AllowDrop = true;
				rectangle.AddHandler(Rectangle.DragEnterEvent, new DragEventHandler(dropRect_DragEnter_1));
				rectangle.AddHandler(Rectangle.DropEvent, new DragEventHandler(dropRect_Drop_1));

				canvasTimeline.Children.Add(rectangle);

			}

			
			//int scaleHeight = 75 + countChannel * 33-3;
			int scaleHeight = 75 + countChannel * (channelVerticalLength+3) - 3;

			Line lineInterval;
			for (int i = 1; i <= totalSecond / 10 + 1; i++)
			{
				lineInterval = new Line();
				lineInterval.Stroke = System.Windows.Media.Brushes.White;
				lineInterval.X1 = i * 100;
				lineInterval.X2 = i * 100;
				lineInterval.Y1 = 75;

				lineInterval.Y2 = scaleHeight;
				lineInterval.HorizontalAlignment = HorizontalAlignment.Left;
				lineInterval.VerticalAlignment = VerticalAlignment.Center;
				lineInterval.StrokeThickness = 1;
				canvasTimeline.Children.Add(lineInterval);
			}




			lineInterval = new Line();
			Color colorTicker = Color.FromRgb(136, 45, 0);
			lineInterval.Stroke = new SolidColorBrush(colorTicker);
			lineInterval.X1 = totalSecond * 10;
			lineInterval.X2 = totalSecond * 10;
			lineInterval.Y1 = 75;

			lineInterval.Y2 = scaleHeight;
			lineInterval.HorizontalAlignment = HorizontalAlignment.Left;
			lineInterval.VerticalAlignment = VerticalAlignment.Center;
			lineInterval.StrokeThickness = 2;
			canvasTimeline.Children.Add(lineInterval);

			fillTimelineChannelResource();

		}

		public void fillTimelineChannelResource()
		{
			int index = 0;
			timelineSelected = campaignSelected.ListTimeline[listviewTimeline.SelectedIndex];

			// filling already saved videos and images in the channels
			foreach (Channel channelTemp in timelineSelected.ListChannel)
			{                
				foreach (Resource resourceTemp in channelTemp.ListResource)
				{
					resourceFileName = resourceTemp.LocalFile.FileName + "." + resourceTemp.LocalFile.FileExt;
					//resourceYPosition = 108 + 33 * index;
					resourceYPosition = 75+channelVerticalLength+3 + (channelVerticalLength+3) * index;
					 RectangleResource rectangleResource = new RectangleResource(this, resourceTemp,channelTemp,false);                    
				}

				index++;
			}
			//

			// filling already saved rss feeds in the channels
			index = 0;
			foreach (Channel channelTemp in timelineSelected.ListChannel)
			{
				foreach (ResourceGraphics resourceTemp in channelTemp.ListResourceGraphics)
				{
					//resourceFileName = resourceTemp.LocalFile.FileName + "." + resourceTemp.LocalFile.FileExt;
					//resourceYPosition = 108 + 33 * index;
					resourceYPosition = 75 + channelVerticalLength + 3 + (channelVerticalLength + 3) * index;
					RectangleResourceGraphics rectangleResourceGraphics = new RectangleResourceGraphics(this, resourceTemp, channelTemp, false);
				}

				index++;
			}
		}


		private void fillTimelineChannelLeft()
		{
			canvasChannel.Children.Clear();


			Rectangle rectangleEmpty = new Rectangle();

			rectangleEmpty.Width = 100;
			rectangleEmpty.Height = 75;

			Canvas.SetLeft(rectangleEmpty, 0);
			Canvas.SetTop(rectangleEmpty, 0);

			rectangleEmpty.Stroke = new SolidColorBrush(Color.FromRgb(155, 47, 7));
			rectangleEmpty.Fill = new SolidColorBrush(Color.FromRgb(155, 47, 7));

			canvasChannel.Children.Add(rectangleEmpty);

			Rectangle rectangleScreenResolution = new Rectangle();
			rectangleScreenResolution.Width = 100;
			//rectangleScreenResolution.Height = 30;
			rectangleScreenResolution.Height = channelVerticalLength;

			Canvas.SetLeft(rectangleScreenResolution, 0);
			Canvas.SetTop(rectangleScreenResolution, 75);

			rectangleScreenResolution.Stroke = new SolidColorBrush(Color.FromRgb(33, 54, 115));
			rectangleScreenResolution.Fill = new SolidColorBrush(Color.FromRgb(33, 54, 115));

			canvasChannel.Children.Add(rectangleScreenResolution);

			
			/*
			TextBlock textBlockScreenResolution = new TextBlock();
			textBlockScreenResolution.Text = campaignSelected.Screen.ScreenName;

			
			
			textBlockScreenResolution.Foreground = new SolidColorBrush(Colors.White);
			
			Canvas.SetLeft(textBlockScreenResolution, 3);
			Canvas.SetTop(textBlockScreenResolution, 82);
			canvasChannel.Children.Add(textBlockScreenResolution);

			 */ 
			/*
			Rectangle rectangleBanckgroundImageText = new Rectangle();
			rectangleBanckgroundImageText.Width = 100;
			rectangleBanckgroundImageText.Height = 30;

			Canvas.SetLeft(rectangleBanckgroundImageText, 0);
			Canvas.SetTop(rectangleBanckgroundImageText, 108);

			rectangleBanckgroundImageText.Stroke = new SolidColorBrush(Color.FromRgb(0,47,0));
			rectangleBanckgroundImageText.Fill = new SolidColorBrush(Color.FromRgb(0, 47, 0));

			canvasChannel.Children.Add(rectangleBanckgroundImageText);

			TextBlock textBlockBackGroundImage = new TextBlock();
			textBlockBackGroundImage.Text = "CH0";



			textBlockBackGroundImage.Foreground = new SolidColorBrush(Colors.White);

			Canvas.SetLeft(textBlockBackGroundImage, 3);
			Canvas.SetTop(textBlockBackGroundImage, 115);
			canvasChannel.Children.Add(textBlockBackGroundImage);

			 * 
			 */ 
			int countChannel = timelineSelected.ScTemplate.ListScreenDivision.Count();

			for (int i = 0; i < countChannel; i++)
			{
				Rectangle rectangle = new Rectangle();

				rectangle.Width = 100;
				//rectangle.Height = 30;
				rectangle.Height = channelVerticalLength;

				Canvas.SetLeft(rectangle, 0);
				//Canvas.SetTop(rectangle, i*33+108);
				Canvas.SetTop(rectangle, i * (channelVerticalLength+3) + 75 +channelVerticalLength+3);

				rectangle.Stroke = new SolidColorBrush(Color.FromRgb(40,0,40));
				rectangle.Fill = new SolidColorBrush(Color.FromRgb(40, 0, 40));

				canvasChannel.Children.Add(rectangle);

				Rectangle rectangleInnner = new Rectangle();

				rectangleInnner.Width = 13;
				rectangleInnner.Height = 13;

				Canvas.SetLeft(rectangleInnner, 10);
				//Canvas.SetTop(rectangleInnner, i * 33 + 117);
				Canvas.SetTop(rectangleInnner, i * (channelVerticalLength + 3) + 75 + channelVerticalLength + 12);

				rectangleInnner.Stroke = new SolidColorBrush(Colors.LightGray);
				rectangleInnner.Fill = new SolidColorBrush(drawing.colorsRect[i]);
				rectangleInnner.StrokeThickness = 1;

				canvasChannel.Children.Add(rectangleInnner);

				TextBlock textBlockChannelName = new TextBlock();
				textBlockChannelName.Text = "CH";


				textBlockChannelName.Foreground = new SolidColorBrush(Colors.White);

				Canvas.SetLeft(textBlockChannelName, 28);
				//Canvas.SetTop(textBlockChannelName, i * 33 + 114);
				Canvas.SetTop(textBlockChannelName, i * (channelVerticalLength+3) + 75+channelVerticalLength+9);
				canvasChannel.Children.Add(textBlockChannelName);
			}

		}


		private void drawLinearScaleForTimeLine(int totalSecond)
		{
			canvasTimeline.Children.Clear();
			
			Rectangle linearScaleRectangle = new Rectangle();

			LinearGradientBrush brushGradientLinearScale = new LinearGradientBrush();
			/*
			brushGradientLinearScale.GradientStops.Add(new GradientStop(Colors.DarkBlue, 0.0));
			//brushGradientLinearScale.GradientStops.Add(new GradientStop(Colors.Blue, 0.5));
			brushGradientLinearScale.GradientStops.Add(new GradientStop(Color.FromRgb(145, 150, 213), 1.0));
			*/
			brushGradientLinearScale.GradientStops.Add(new GradientStop(Color.FromRgb(37, 12, 52), 0.0));
			brushGradientLinearScale.GradientStops.Add(new GradientStop(Color.FromRgb(88, 63, 95), 0.4));
			brushGradientLinearScale.GradientStops.Add(new GradientStop(Color.FromRgb(44, 56, 142), 1.0));


			linearScaleRectangle.Fill = brushGradientLinearScale;
			//linearScaleRectangle.Fill = new SolidColorBrush(Colors.Black);
			
			linearScaleRectangle.Width = totalSecond*10+150;
			linearScaleRectangle.Height = 75;
			Canvas.SetLeft(linearScaleRectangle, 0);
			Canvas.SetTop(linearScaleRectangle, 0);

			canvasTimeline.Children.Add(linearScaleRectangle);


			if (linearScaleRectangle.Width > 1000)
			{
				canvasTimeline.Width = linearScaleRectangle.Width + 40;
			}
			else
			{
				canvasTimeline.Width = 1000;
			}

			int countChannel = timelineSelected.ScTemplate.ListScreenDivision.Count() + 2;
			canvasTimeline.Height = 75 + countChannel * (channelVerticalLength+3) + 40;
			
			// drawing minor ticks
			for (int i = 1; i <= totalSecond+9; i++)
			{
				Line lineMinorTick = new Line();
				lineMinorTick.Stroke = System.Windows.Media.Brushes.White;
				lineMinorTick.X1 = i * 10;
				lineMinorTick.X2 = i * 10;
				lineMinorTick.Y1 = 33;
				lineMinorTick.Y2 = 40;
				lineMinorTick.HorizontalAlignment = HorizontalAlignment.Left;
				lineMinorTick.VerticalAlignment = VerticalAlignment.Center;
				lineMinorTick.StrokeThickness = 1;
				canvasTimeline.Children.Add(lineMinorTick);
			}

			//

			// drawing major ticks
			Line lineMajorTick;
			for (int i = 1; i <= totalSecond /10+1; i++)
			{
				lineMajorTick = new Line();
				lineMajorTick.Stroke = System.Windows.Media.Brushes.Orange;
				lineMajorTick.X1 = i * 100;
				lineMajorTick.X2 = i * 100;
				lineMajorTick.Y1 = 0;
				lineMajorTick.Y2 = 40;
				lineMajorTick.HorizontalAlignment = HorizontalAlignment.Left;
				lineMajorTick.VerticalAlignment = VerticalAlignment.Center;
				lineMajorTick.StrokeThickness = 2;
				canvasTimeline.Children.Add(lineMajorTick);
			}

			lineMajorTick = new Line();
			lineMajorTick.Stroke = new SolidColorBrush(Color.FromRgb(136,45,0));
			lineMajorTick.X1 = totalSecond * 10;
			lineMajorTick.X2 = totalSecond * 10;
			lineMajorTick.Y1 = 0;
			lineMajorTick.Y2 = 40;
			lineMajorTick.HorizontalAlignment = HorizontalAlignment.Left;
			lineMajorTick.VerticalAlignment = VerticalAlignment.Center;
			lineMajorTick.StrokeThickness = 2;
			canvasTimeline.Children.Add(lineMajorTick);


			//
			// drawing major time labels
			TextBlock textBlock;

			for (int i = 1; i <= totalSecond / 10+1; i++)
			{
				textBlock = new TextBlock();
				textBlock.Text = getHourMinuteSecondStringFromSecond(i*10);

				if (i == totalSecond / 10)
				{
					textBlock.Foreground = new SolidColorBrush(Color.FromRgb(136, 45, 0));
				}
				else
				{
					textBlock.Foreground = new SolidColorBrush(Colors.Orange);
				}
				Canvas.SetLeft(textBlock,i*100-20 );
				Canvas.SetTop(textBlock, 50);
				canvasTimeline.Children.Add(textBlock);
			}

			

			//

			Polygon tickerPolygon = new Polygon();
			Point point1 = new Point(totalSecond*10-7,33);
			Point point2 = new Point(totalSecond*10+7,33);
			Point point3 = new Point(totalSecond*10,40);

			tickerPolygon.Points.Add(point1);
			tickerPolygon.Points.Add(point2);
			tickerPolygon.Points.Add(point3);
			tickerPolygon.Points.Add(point1);

			Color colorTicker = Color.FromRgb(136,45,0);


			tickerPolygon.Stroke = new SolidColorBrush(colorTicker);
			tickerPolygon.StrokeThickness = 2;
			tickerPolygon.Fill = new SolidColorBrush(colorTicker);

			canvasTimeline.Children.Add(tickerPolygon);
			canvasTimeline.UpdateLayout();
		}

		private string getHourMinuteSecondStringFromSecond(int second)
		{
			int sec = second % 60;
			int hr = second / 3600;
			int min = (second - hr * 3600) / 60;

			string combinedString = get2digitFigure(hr) + ":" + get2digitFigure(min) + ":" + get2digitFigure(sec);
			return combinedString;
		}

		private string get2digitFigure(int value)
		{
			if (value < 10)
			{
				return "0" + value;
			}
			else
			{
				return Convert.ToString(value);
			}
		}


		private void drawMajorTicksForLinearScaleTimeline(int totalSecond)
		{

		}


		private void Button_Delete_Timeline_Click_1(object sender, RoutedEventArgs e)
		{
			MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("Are you sure?", "Timeline Delete Confirmation", System.Windows.MessageBoxButton.YesNo);
			if (messageBoxResult == MessageBoxResult.Yes)
			{
				/*
				TimelineDAO timelineDAO = TimelineDAO.getTimelineSingleTon();
				int successDel = timelineDAO.deleteTimelineObject(timelineSelected);
				listTimeline = timelineDAO.getTimelineObject();
				listviewTimeline.ItemsSource = null;
				listviewTimeline.ItemsSource = listTimeline;
				gridTimelineProperty.Visibility = Visibility.Collapsed;
				 */
				Timeline timelineSelected = listviewTimeline.SelectedItem as Timeline;
				campaignSelected = listCampaign[listViewCampaign.SelectedIndex];

				CampaignDAO campaignDAO = CampaignDAO.getSingleTon();
				campaignDAO.deleteTimelineFromCampaign(campaignSelected, timelineSelected);
				campaignDAO.saveListToFile(listCampaign);

				listviewTimeline.ItemsSource = null;
				listviewTimeline.ItemsSource = campaignSelected.getTimeline();
				gridTimelineProperty.Visibility = Visibility.Collapsed;
			}
		}

		private void Window_Loaded_1(object sender, RoutedEventArgs e)
		{
			// Create the interop host control.
			host = new WindowsFormsHost();
			// Create the ActiveX control.
			//AxShockwaveFlash axShockwaveFlash = new AxShockwaveFlash();
			//axswf = new AxShockwaveFlash();
			// Assign the ActiveX control as the host control's child.
			//host.Child = axShockwaveFlash;
			//host.Child = axswf;

			// Add the interop host control to the Grid
			// control's collection of child controls.
			//this.flashgrid.Children.Add(host);
			//axShockwaveFlash.Location = new System.Drawing.Point(0, 0);
			//this.Show() // Avoids InvalidActiveXStateException
			//axShockwaveFlash.LoadMovie(0, @"C:\BUET.swf");

			/*
			axShockwaveFlash.LoadMovie(0, @"file://" + System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Resources\BUET- Registrar Building.swf");
			axShockwaveFlash.SetVariable("quality", "Low");
			axShockwaveFlash.ScaleMode = 1;
			axShockwaveFlash.AlignMode = 0;
			axShockwaveFlash.AllowFullScreen = "true";
			axShockwaveFlash.AllowScriptAccess = "always";
			 */

			//Console.WriteLine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
			//axShockwaveFlash.FlashVars =  @"file=C:\barsandtone.flv" + 
			//&autostart=true&fullscreen=true&controlbar=none&repeat=" +
			//"always&stretching=fill";

			/*
			axShockwaveFlash.CallFunction("<invoke name=\"loadFLV\" " +
				"returntype=\"xml\"><arguments><string>barsandtone.flv</string>" +
				"</arguments></invoke>");
			*/

			//axShockwaveFlash.Play();
			this.FontChooser.SelectionChanged += new SelectionChangedEventHandler(FontChooser_SelectionChanged_1);
			this.rssFontChooser.SelectionChanged += new SelectionChangedEventHandler(rssFontChooser_SelectionChanged_1);
            this.comboboxTextAlignment.SelectionChanged += new SelectionChangedEventHandler(comboboxTextAlignment_SelectionChanged_1);
		}

		private void Button_PlayCampaign_Click_1(object sender, RoutedEventArgs e)
		{
			/*
			(sender as System.Windows.Controls.Button).ContextMenu.IsEnabled = true;
			(sender as System.Windows.Controls.Button).ContextMenu.PlacementTarget = (sender as System.Windows.Controls.Button);
			(sender as System.Windows.Controls.Button).ContextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
			(sender as System.Windows.Controls.Button).ContextMenu.IsOpen = true;
			*/
			
			if (flagCamapaignOn)
			{
				//timerCampaign.Start();
				timerCampaign2.Enabled = true;
				timelinecomponent.resume() ;
				/*
				if (storyBoardCampaignCanvas != null)
				{
					storyBoardCampaignCanvas.Resume();
				}
				 */
			}
			else
			{
				if (mediaElementCanvasCampaign != null)
				{
					mediaElementCanvasCampaign.Play();                    
				}
				if (storyBoardCampaignCanvas != null)
				{
					storyBoardCampaignCanvas.Resume();
				}
			}
			
		}

		/*
		private void swfitem_Click_1(object sender, RoutedEventArgs e)
		{

		}

		private void flvitem_Click_1(object sender, RoutedEventArgs e)
		{
			axswf = new AxShockwaveFlash();
			host.Child = axswf;
			this.flashgrid.Children.Add(host);
			//axswf.LoadMovie(0, @"file://" + System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Resources\BUET- Registrar Building.swf");
			axswf.LoadMovie(0, @"file://" + System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Resources\player.swf");
			axswf.SetVariable("quality", "Low");
			//axswf.ScaleMode = 1;
			//axswf.AlignMode = 0;
			//axswf.AllowFullScreen = "true";
			//axswf.AllowScriptAccess = "always";
			//axswf.EmbedMovie = true;
			//axswf.FlashVars = @"flv=C:\Outlander.flv";
			//axswf.SetVariable("file", @"C:\Outlander.flv");

			// this code for loading flv
			string flvfilename = System.AppDomain.CurrentDomain.BaseDirectory + "Resources\\" + "Outlander.flv";

			axswf.CallFunction("<invoke name=\"loadAndPlayVideo\" " +
				"returntype=\"xml\"><arguments><string>" + flvfilename + "</string>" +
				"</arguments></invoke>");
			axswf.Play();
		}

		private void wmvitem_Click_1(object sender, RoutedEventArgs e)
		{
			if (axswf != null)
			{
				if (axswf.IsPlaying() == true)
				{
					axswf.Stop();
				}
				axswf.Dispose();
			}
			
			this.flashgrid.Children.Remove(host);
			MediaElement mediall = new MediaElement();
			string wmvFileName = System.AppDomain.CurrentDomain.BaseDirectory + "Resources\\" + "Video_00001.wmv";
			string avifilename = System.AppDomain.CurrentDomain.BaseDirectory + "Resources\\" + "Lie.to.Me.avi";
			string flvfilename = System.AppDomain.CurrentDomain.BaseDirectory + "Resources\\" + "Outlander.flv";
			mediall.Source = new Uri(flvfilename, UriKind.Absolute);
			mediall.LoadedBehavior = MediaState.Play;
			this.flashgrid.Children.Add(mediall);
		}
		*/
		private void Button_Add_Campaign_Click_1(object sender, RoutedEventArgs e)
		{
			AddCampainWindow addCampaignWindow = new AddCampainWindow(listScreen);
			addCampaignWindow.Owner = this;
			addCampaignWindow.Owner.ShowActivated = false;
			bool? result = addCampaignWindow.ShowDialog();


			if (result != null)
			{
				if (result == true)
				{
					
					//listViewScreen.ItemsSource = null;
					CampaignDAO campaignDAO = CampaignDAO.getSingleTon();
					listCampaign = campaignDAO.getAll();
					listViewCampaign.ItemsSource = listCampaign ;
					ICollectionView view = CollectionViewSource.GetDefaultView(listViewCampaign.ItemsSource);
					view.Refresh();
				}
			}
		}

		private void Button_Delete_Campaign_Click_1(object sender, RoutedEventArgs e)
		{
			MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("Are you sure?", "ScreenTemplate Delete Confirmation", System.Windows.MessageBoxButton.YesNo);
			if (messageBoxResult == MessageBoxResult.Yes)
			{
				CampaignDAO campaignDAO = CampaignDAO.getSingleTon();
				Campaign campaignToBeDeleted = listViewCampaign.SelectedItem as Campaign;
				campaignDAO.deleteCampaign(campaignToBeDeleted);
				listCampaign = campaignDAO.getAll();

				listViewCampaign.ItemsSource = listCampaign;
				ICollectionView view = CollectionViewSource.GetDefaultView(listViewCampaign.ItemsSource);
				view.Refresh();
				listviewTimeline.ItemsSource = null;
				canvasChannel.Children.Clear();
				canvasTimeline.Children.Clear();

			}
		}

		private void textBoxTimelineName_KeyUp_1(object sender, KeyEventArgs e)
		{
			if (e.Key == Key.Enter)
			{
				BindingExpression be = textBoxTimelineName.GetBindingExpression(System.Windows.Controls.TextBox.TextProperty);
				be.UpdateSource();
				CampaignDAO campaignDAO = CampaignDAO.getSingleTon();                
				campaignSelected.ListTimeline[listviewTimeline.SelectedIndex].Name = textBoxTimelineName.Text ;
				campaignDAO.updateCampaign(campaignSelected);
			}
		}
		/*
		private void Button_Add_Channel_Click_1(object sender, RoutedEventArgs e)
		{

		}
		*/
		private void listViewFile_PreviewMouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
		{
			// Store the mouse position
			startPoint = e.GetPosition(null);
		}

		private void listViewFile_PreviewMouseMove_1(object sender, MouseEventArgs e)
		{
			// Get the current mouse position
			Point mousePos = e.GetPosition(null);
			Vector diff = startPoint - mousePos;

			if (e.LeftButton == MouseButtonState.Pressed &&
				(Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
				Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance))
			{
				// Get the dragged ListViewItem
				ListView listView = sender as ListView;
				ListViewItem listViewItem =
					FindAnchestor<ListViewItem>((DependencyObject)e.OriginalSource);

				if (listViewItem == null) return;

				// Find the data behind the ListViewItem
				LocalFile localFileDragged = (LocalFile)listView.ItemContainerGenerator.
					ItemFromContainer(listViewItem);

				// Initialize the drag & drop operation
				DataObject dragData = new DataObject(typeof(LocalFile), localFileDragged );
				DragDrop.DoDragDrop(listViewItem, dragData, DragDropEffects.Move);
			} 
		}

		// Helper to search up the VisualTree
		private static T FindAnchestor<T>(DependencyObject current)
			where T : DependencyObject
		{
			do
			{
				if (current is T)
				{
					return (T)current;
				}
				current = VisualTreeHelper.GetParent(current);
			}
			while (current != null);
			return null;
		}

		private void dropRect_DragEnter_1(object sender, DragEventArgs e)
		{
			if (!e.Data.GetDataPresent(typeof(LocalFile)) || sender == e.Source)
			{
				//e.Effects = DragDropEffects.None;
			}            
		}

		private void dropRect_Drop_1(object sender, DragEventArgs e)
		{
			if (e.Data.GetDataPresent(typeof(LocalFile)))
			{
				LocalFile localFileDropped = e.Data.GetData(typeof(LocalFile)) as LocalFile;
				
				
				rectangleResourceCurrent = sender as Rectangle;

				int indexRectangle = listChannelRectangle.IndexOf(rectangleResourceCurrent)-1;

				Timeline timelineTemp = campaignSelected.ListTimeline[listviewTimeline.SelectedIndex] ;
				channelSelected = timelineTemp.ListChannel[indexRectangle];
				//channelSelected = timelineSelected.ListChannel[indexRectangle];

				xDragRectangleTimeline = e.GetPosition(canvasTimeline).X;
				yDragRectangleTimeline = e.GetPosition(canvasTimeline).Y;


				Resource resource = new Resource(localFileDropped);
				resource.Offset = Convert.ToInt32(xDragRectangleTimeline / 10);

				
				//resource.Duration = 20;
				//channelSelected.ListResource.Add(resource);

				resourceFileName = localFileDropped.FileName + "." + localFileDropped.FileExt;
				resource.Duration = localFileDropped.TimeDuration;
				
				RectangleResource resourceResource = new RectangleResource(this, resource,channelSelected,true);

				//campaignSelected = listCampaign[listViewCampaign.SelectedIndex];

				CampaignDAO campaignDAO = CampaignDAO.getSingleTon();
				campaignDAO.updateCampaign(campaignSelected);
				
				

				/*
				ImageBrush uniformBrush = new ImageBrush();
				uniformBrush.ImageSource = new BitmapImage(new Uri(System.AppDomain.CurrentDomain.BaseDirectory + "Resources\\"+fileNamewithExt, UriKind.Absolute));
				//uniformBrush.Stretch = Stretch.None;
				
				uniformBrush.Viewport = new Rect(0.25, 0, 0.5, 1);
				uniformBrush.TileMode = TileMode.None;
				Rectangle rectangleResource = new Rectangle();

				
				rectangleResource.Width = 200;
				rectangleResource.Height = 30;

				rectangleResource.Stroke = Brushes.Red;
				rectangleResource.StrokeThickness = 2;
				//rectangleResource.Fill = new SolidColorBrush(Colors.DarkBlue);

				rectangleResource.Fill = uniformBrush;

				Canvas.SetLeft(rectangleResource, x);
				Canvas.SetTop(rectangleResource, y);

				canvasTimeline.Children.Add(rectangleResource);
				*/ 

				//Console.WriteLine("x:" + e.GetPosition(canvasTimeline).X + ",y:" + e.GetPosition(canvasTimeline).Y);

			}
			else  
			{
				Label labelDragged = e.Data.GetData(typeof(Label)) as Label;
				if (labelDragged.Name.Equals("labelRSS"))
				{
					//Console.WriteLine("rss dragged");
					rectangleResourceCurrent = sender as Rectangle;

					int indexRectangle = listChannelRectangle.IndexOf(rectangleResourceCurrent)-1;
					Timeline timelineTemp = campaignSelected.ListTimeline[listviewTimeline.SelectedIndex] ;
					channelSelected = timelineTemp.ListChannel[indexRectangle];

					xDragRectangleTimeline = e.GetPosition(canvasTimeline).X;
					yDragRectangleTimeline = e.GetPosition(canvasTimeline).Y;

					resourceRSS.Offset = Convert.ToInt32(xDragRectangleTimeline / 10);
                    
					

					// saving the rectangle graphics resource to database, by updating channel's listResourceGraphics
					
                    threadRSS = new Thread(new ThreadStart(updateRSStitles));
                    threadRSS.Start();
					Console.WriteLine(resourceRSS.StrAllNewsTitles);
					RectangleResourceGraphics rectangleResourceGraphics = new RectangleResourceGraphics(this, resourceRSS, channelSelected, true);
                    CampaignDAO campaignDAO = CampaignDAO.getSingleTon();
                    campaignDAO.updateCampaign(campaignSelected);
					//
				}
                else if (labelDragged.Name.Equals("labelToDrag"))
				{
                    Console.WriteLine("text label dragged");
                    rectangleResourceCurrent = sender as Rectangle;

                    int indexRectangle = listChannelRectangle.IndexOf(rectangleResourceCurrent) - 1;
                    Timeline timelineTemp = campaignSelected.ListTimeline[listviewTimeline.SelectedIndex];
                    channelSelected = timelineTemp.ListChannel[indexRectangle];

                    xDragRectangleTimeline = e.GetPosition(canvasTimeline).X;
                    yDragRectangleTimeline = e.GetPosition(canvasTimeline).Y;

                    resourceText.Offset = Convert.ToInt32(xDragRectangleTimeline / 10);



                    // saving the rectangle graphics resource to database, by updating channel's listResourceGraphics
                    CampaignDAO campaignDAO = CampaignDAO.getSingleTon();
                    campaignDAO.updateCampaign(campaignSelected);
                    
                    //Console.WriteLine(resourceRSS.StrAllNewsTitles);
                    RectangleResourceGraphics rectangleResourceGraphics = new RectangleResourceGraphics(this, resourceText, channelSelected, true);
					
				}
			}
		}

        private void updateRSStitles()
        {
            resourceRSS.StrAllNewsTitles = RssUtil.getAllTitlesCombined(resourceRSS.RssSource);
        }





		private void listViewCampaign_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
		{
			if (listViewCampaign.SelectedItem != null)
			{
				campaignSelected = listCampaign[listViewCampaign.SelectedIndex];
				CampaignDAO campaignDAO = CampaignDAO.getSingleTon();

				List<Timeline> listTimeline = campaignDAO.getTimelineListByCampaign(campaignSelected);

				listviewTimeline.ItemsSource = null;
				listviewTimeline.ItemsSource = listTimeline;

				if (listTimeline.Count > 0)
				{
					listviewTimeline.SelectedIndex = 0;
					listviewTimeline_SelectionChanged_1(null, null);
				}
			}
		}

		private void drawGraphics()
		{
			Rectangle backgroundRect = new Rectangle();
			backgroundRect.Width = 80;
			backgroundRect.Height = 100;
			backgroundRect.StrokeThickness = 2;
			backgroundRect.Stroke = Brushes.DarkSalmon;
			ImageBrush backBrush = new ImageBrush();
			backBrush.ImageSource =
				new BitmapImage(
					new Uri(System.AppDomain.CurrentDomain.BaseDirectory + "Resources\\" + "kakashi.jpg", UriKind.Absolute)
				);
			//backBrush.Stretch = Stretch.None;
			backBrush.Viewport = new Rect(0, 0, 0.5, 0.5);
			backBrush.TileMode = TileMode.None;
			backgroundRect.Fill = backBrush;
			Canvas.SetLeft(backgroundRect, 30);
			Canvas.SetTop(backgroundRect, 60);
			Canvas.SetZIndex(backgroundRect, 0);
			this.campaignCanvas.Children.Add(backgroundRect);


			
			Rectangle videoRect = new Rectangle();
			videoRect.Width = 150;
			videoRect.Height = 100;
			MediaElement myMediaElement = new MediaElement();
			myMediaElement.Source = new Uri(System.AppDomain.CurrentDomain.BaseDirectory + "Resources\\" + "Outlander.flv", UriKind.Absolute);
			myMediaElement.LoadedBehavior = MediaState.Play;
			VisualBrush myVisualBrush = new VisualBrush();
			
			
			// myVisualBrush.Viewport = new Rect(0, 0, 0.5, 0.5);
			//myVisualBrush.TileMode = TileMode.Tile;
			myVisualBrush.Visual = myMediaElement;
			videoRect.Fill = myVisualBrush;
			Canvas.SetLeft(videoRect, 50);
			Canvas.SetTop(videoRect, 80);
			Canvas.SetZIndex(videoRect, 1);
			this.campaignCanvas.Children.Add(videoRect);
		}

		private void textBoxResourceName_KeyUp_1(object sender, KeyEventArgs e)
		{

		}

		private void textBoxResourceOffset_KeyUp_1(object sender, KeyEventArgs e)
		{

		}

		private void listviewTimeline_PreviewMouseLeftButtonUp_1(object sender, MouseButtonEventArgs e)
		{
			gridTimelineProperty.Visibility = Visibility.Visible;
			gridResourceProperty.Visibility = Visibility.Collapsed;



		}

		private void spinnerResourceDuration_ValueChanged_1(object sender, System.Windows.RoutedPropertyChangedEventArgs<object> e)
		{
			if (rectangleResourceSelected != null)
			{
				rectangleResourceSelected.Resource.Duration = Convert.ToInt32(((TimeSpan)spinnerResourceDuration.Value).TotalSeconds);
				rectangleResourceSelected.updateRectangle();                
			}
		}

		private void spinnerResourceOffset_ValueChanged_1(object sender, System.Windows.RoutedPropertyChangedEventArgs<object> e)
		{
			if (rectangleResourceSelected != null)
			{
				rectangleResourceSelected.Resource.Offset = Convert.ToInt32(((TimeSpan)spinnerResourceOffset.Value).TotalSeconds);
				rectangleResourceSelected.updateRectangle();                
			}
		}

		private void Button_PauseCampaign_Click_1(object sender, RoutedEventArgs e)
		{
			//mediaElementCanvasCampaign.LoadedBehavior = MediaState.Manual;
			
			if (flagCamapaignOn)
			{
				//timerCampaign.Stop();
				timerCampaign2.Enabled = false;
				timelinecomponent.pause();                    
			}
			else
			{
				if (mediaElementCanvasCampaign != null)
				{
					mediaElementCanvasCampaign.Pause();                    
				}
				if (storyBoardCampaignCanvas != null)
				{
					storyBoardCampaignCanvas.Pause();
				}
			}
			
		}

		
		private void Button_StopCampaign_Click_1(object sender, RoutedEventArgs e)
		{
			if(flagCamapaignOn)
			{
			}
			else
			{
				if (mediaElementCanvasCampaign != null)
				{
					mediaElementCanvasCampaign.Stop();
				}
			} 
		}

		private void tick(object sender, EventArgs e)
		{
			timeSecond++;
			Dispatcher.BeginInvoke((Action)delegate()
				{
					timeSpanUpDown.Value = TimeSpan.FromSeconds(timeSecond);
				});            
			//Console.WriteLine("timer output");
		}

		private void textboxLabelText_KeyUp_1(object sender, KeyEventArgs e)
		{
			if (e.Key == Key.Enter)
			{
				labelToDrag.Content = textboxLabelText.Text;
			}
		}

		private void FontChooser_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
		{
			if (FontChooser.SelectedValue != null)
			{
				labelToDrag.FontFamily = new System.Windows.Media.FontFamily(FontChooser.SelectedValue.ToString());
			}
		}

		private void labelColorPicker_SelectedColorChanged_1(object sender, System.Windows.RoutedPropertyChangedEventArgs<Color> e)
		{
			labelToDrag.Foreground = new SolidColorBrush(labelColorPicker.SelectedColor);
		}

		private void imageRss_DragLeave_1(object sender, DragEventArgs e)
		{
			Console.WriteLine("Drag left for rss image");
		}

		private void labelRSS_MouseDown_1(object sender, MouseButtonEventArgs e)
		{
			resourceRSS = new ResourceRSS();
            //resourceRSS.TypeName = "rss";
			resourceRSS.DirectionText = (EnumAll.DirectionText)comboboxRSStext.SelectedIndex;
            Console.WriteLine("dir: " + resourceRSS.DirectionText.getDirectionScroll());
            resourceRSS.Duration = 20;            
			resourceRSS.RssSource = (RSSSource)comboboxRSSSource.SelectedIndex;
			resourceRSS.IsBold = this.isRssBold;
			resourceRSS.IsUnderlined = this.isRssUnderline;
			resourceRSS.IsItalic = this.isRssItalic;
			resourceRSS.FontFamily = this.rssFontFamily;
			resourceRSS.TextColor = new ColorCustom();
			resourceRSS.TextColor.Red = Convert.ToInt32(this.rssColorPicker.SelectedColor.R.ToString());
			resourceRSS.TextColor.Green = Convert.ToInt32(this.rssColorPicker.SelectedColor.G.ToString());
			resourceRSS.TextColor.Blue = Convert.ToInt32(this.rssColorPicker.SelectedColor.B.ToString());

			//Console.WriteLine(resourceRSS.IsBold);
			DataObject dragData = new DataObject(typeof(Label), labelRSS);
			DragDrop.DoDragDrop(labelRSS, dragData, DragDropEffects.Move);
			//Label label = sender as Label;
			//DragDrop.DoDragDrop(label, label.Content, DragDropEffects.Move);
			Console.WriteLine("Drag left for rss label");
		}

		private void toggleButtonUnderlineRSS_Checked_1(object sender, RoutedEventArgs e)
		{
			this.isRssUnderline = true;
		}

		private void toggleButtonBoldRSS_Checked_1(object sender, RoutedEventArgs e)
		{
			//Console.WriteLine("toggle checked");
			this.isRssBold = true;
		}

		private void toggleButtonBoldRSS_Unchecked_1(object sender, RoutedEventArgs e)
		{
			//Console.WriteLine("toggle unchecked");
			this.isRssBold = false;
		}

		private void toggleButtonUnderlineRSS_Unchecked_1(object sender, RoutedEventArgs e)
		{
			this.isRssUnderline = false;
		}

		private void toggleButtonItalicRSS_Checked_1(object sender, RoutedEventArgs e)
		{
			this.isRssItalic = true;
		}

		private void toggleButtonItalicRSS_Unchecked_1(object sender, RoutedEventArgs e)
		{
			this.isRssItalic = false;
		}

		private void rssColorPicker_SelectedColorChanged_1(object sender, System.Windows.RoutedPropertyChangedEventArgs<Color> e)
		{
			/*
			if (resourceRSS.TextColor == null)
			{
				Console.WriteLine("color is null");
			}
			resourceRSS.TextColor.Red = Convert.ToInt32(this.rssColorPicker.SelectedColor.R.ToString());
			 */
			//Console.WriteLine(this.rssColor.ToString());
		}

		private void rssFontChooser_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
		{
			if (rssFontChooser.SelectedValue != null)
			{
				this.rssFontFamily = rssFontChooser.SelectedValue.ToString();
			}
		}

        private void toggleButtonBold_Checked_1(object sender, RoutedEventArgs e)
        {
            labelToDrag.FontWeight = FontWeights.Bold;
        }

        private void toggleButtonBold_Unchecked_1(object sender, RoutedEventArgs e)
        {
            labelToDrag.FontWeight = FontWeights.Normal;
        }

        private void toggleButtonItalic_Checked_1(object sender, RoutedEventArgs e)
        {
            labelToDrag.FontStyle = FontStyles.Italic;
        }

        private void toggleButtonItalic_Unchecked_1(object sender, RoutedEventArgs e)
        {
            labelToDrag.FontStyle = FontStyles.Normal;
        }

        private void toggleButtonUnderline_Checked_1(object sender, RoutedEventArgs e)
        {
            TextBlock tb = new TextBlock();
            tb.Text = labelToDrag.Content.ToString();
            TextDecorationCollection tdc = new TextDecorationCollection();
            TextDecoration underline = new TextDecoration(); // underline is the default
            tdc.Add(underline);
            tb.TextDecorations = tdc;
            labelToDrag.Content = tb;
        }

        private void toggleButtonUnderline_Unchecked_1(object sender, RoutedEventArgs e)
        {
            TextBlock tb = new TextBlock();
            tb = (TextBlock)labelToDrag.Content;
            tb.TextDecorations = null;
            labelToDrag.Content = tb.Text.ToString();
        }

        private void comboboxTextAlignment_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            /*
            if(comboboxTextAlignment.SelectedIndex==0)
            {
                labelToDrag.HorizontalContentAlignment = HorizontalAlignment.Left;
            }
            else if (comboboxTextAlignment.SelectedIndex == 1)
            {
                labelToDrag.HorizontalContentAlignment = HorizontalAlignment.Right;
            }
            else if (comboboxTextAlignment.SelectedIndex == 2)
            {
                labelToDrag.HorizontalContentAlignment = HorizontalAlignment.Center;
            }
             */
            labelToDrag.HorizontalContentAlignment = (HorizontalAlignment)comboboxTextAlignment.SelectedIndex;
            /*
            else if (comboboxTextAlignment.SelectedIndex == 3)
            {
                TextBlock tb = new TextBlock();
                tb = (TextBlock)labelToDrag.Content;
                tb.TextAlignment = 
            }
             */
            // justify = 3;
        }

        private void labelToDrag_MouseDown_1(object sender, MouseButtonEventArgs e)
        {
            resourceText = new ResourceText();
          //  resourceText.TypeName = "label";
            resourceText.Duration = 20;
            resourceText.LabelText = labelToDrag.Content.ToString();
     //       resourceText.FontFamily = labelToDrag.FontFamily.Source;
            //Console.WriteLine(resourceText.FontFamily);
            DataObject dragData = new DataObject(typeof(Label), labelToDrag);
            DragDrop.DoDragDrop(labelToDrag, dragData, DragDropEffects.Move);
           
            //Console.WriteLine("Drag left for text label");
        }
		

	}
}
